package org.alwayssuper.protocol.commons.transform.realtimev2025.enums;

/**
 * 挡位状态枚举 (整车数据 0x01)
 * 基于 GB/T 32960.3-2025 标准
 * 挡位状态字节格式：
 * Bit7: 1:挡位无效 0:挡位有效
 * Bit6: 预留
 * Bit5: 1:有驱动力 0:无驱动力  
 * Bit4: 1:有制动力 0:无制动力
 * Bit3-Bit0: 挡位值
 * @author alwaysSuper
 */
public enum GearStatus {
    NEUTRAL(0x00, "空挡"),
    GEAR_1(0x01, "1挡"),
    GEAR_2(0x02, "2挡"),
    GEAR_3(0x03, "3挡"),
    GEAR_4(0x04, "4挡"),
    GEAR_5(0x05, "5挡"),
    GEAR_6(0x06, "6挡"),
    GEAR_7(0x07, "7挡"),
    GEAR_8(0x08, "8挡"),
    GEAR_9(0x09, "9挡"),
    GEAR_10(0x0A, "10挡"),
    GEAR_11(0x0B, "11挡"),
    GEAR_12(0x0C, "12挡"),
    REVERSE(0x0D, "倒挡"),
    AUTO_D(0x0E, "自动D挡"),
    PARK(0x0F, "停车P挡"),
    ABNORMAL(0xFE, "异常"),
    INVALID(0xFF, "无效");

    private final int code;
    private final String description;

    GearStatus(int code, String description) {
        this.code = code;
        this.description = description;
    }

    public int getCode() {
        return code;
    }

    public String getDescription() {
        return description;
    }

    /**
     * 从完整挡位字节解析挡位值
     * @param gearByte 完整挡位字节
     * @return 挡位状态
     */
    public static GearStatus fromGearByte(int gearByte) {
        // 提取低4位作为挡位值
        int gearValue = gearByte & 0x0F;
        return fromCode(gearValue);
    }

    /**
     * 从挡位值获取挡位状态
     * @param code 挡位值(0x00-0x0F)
     * @return 挡位状态
     */
    public static GearStatus fromCode(int code) {
        for (GearStatus gear : values()) {
            if (gear.code == code) {
                return gear;
            }
        }
        return INVALID;
    }

    /**
     * 检查挡位是否有效
     * @param gearByte 完整挡位字节
     * @return true:有效 false:无效
     */
    public static boolean isGearValid(int gearByte) {
        return (gearByte & 0x80) == 0;
    }

    /**
     * 检查是否有驱动力
     * @param gearByte 完整挡位字节
     * @return true:有驱动力 false:无驱动力
     */
    public static boolean hasDrivingForce(int gearByte) {
        return (gearByte & 0x20) != 0;
    }

    /**
     * 检查是否有制动力
     * @param gearByte 完整挡位字节
     * @return true:有制动力 false:无制动力
     */
    public static boolean hasBrakingForce(int gearByte) {
        return (gearByte & 0x10) != 0;
    }

    @Override
    public String toString() {
        return String.format("GearStatus{code=0x%02X, description='%s'}", code, description);
    }
}